//
//  OBDGCDTimer.swift
//  OBD
//
//  Created by sqkj on 2021/9/16.
//

import UIKit

class OBDGCDTimer: NSObject {
    public static var codeTimer: DispatchSourceTimer?

    public class func start(_ timeInterval: TimeInterval = 1,_ totolTimeInterval: TimeInterval = Double(MAXFLOAT), animation: @escaping (_ isFinish: Bool,_ count:TimeInterval )->()){
 
        var timeCount = totolTimeInterval
      
        OBDGCDTimer.codeTimer = DispatchSource.makeTimerSource(queue: DispatchQueue.global())
 
        OBDGCDTimer.codeTimer?.schedule(deadline: .now(), repeating: timeInterval)
        
        var isFinish = false
        
        OBDGCDTimer.codeTimer?.setEventHandler(handler: {
            
            timeCount = timeCount - timeInterval
          
            if timeCount == -1 {
                OBDGCDTimer.codeTimer?.cancel()
                isFinish = true
            }
            
            DispatchQueue.main.async {
                animation(isFinish,timeCount)
            }
            
        })
        
        self.resume()
    }
    
    public class func resume() {
        OBDGCDTimer.codeTimer?.resume()
    }
    
    public class func stop() {
        OBDGCDTimer.codeTimer?.cancel()
    }

}
